#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

#define CHARS 3

#define assert(x, msg)   \
    {                    \
        if (!(x))       \
        {                \
            perror(msg); \
            exit(1);     \
        }                \
    }

// modify content of file by mmap
int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s file\n", argv[0]);
        exit(1);
    }

    int fd = open(argv[1], O_RDWR | O_EXCL);

    if (fd < 0)
    {
        perror("open()");
        exit(1);
    }

    struct stat st;
    assert(fstat(fd, &st) >= 0, "fstat");
    char *p = mmap(NULL, st.st_size, PROT_WRITE, MAP_SHARED, fd, 0);
    assert(p != MAP_FAILED, "mmap");
   
    for(int i = 0; i < CHARS; i++) {
        p[i] = 'a';
    }

    assert(munmap(p, st.st_size) >= 0, "munmap");
    close(fd);
    exit(0);
}